package app

import (
	"log"
	"os"

	"gitee.com/xuender/ds/pb"
	"github.com/BurntSushi/toml"
)

// DSConfig 配置文件.
const DSConfig = "ds.toml"

// ConfigService 配置服务.
type ConfigService struct {
	file     string
	config   *Config
	displays []*pb.Display
	pages    []*pb.Page
	blocks   []*pb.Block
	images   []*pb.Images
	Webs     []*pb.Web
}

// NewConfigService 新配置服务.
func NewConfigService() *ConfigService {
	return NewConfigServiceBy("ds.toml")
}

// NewConfigServiceBy 根据配置文件新建配置服务.
func NewConfigServiceBy(file string) *ConfigService {
	config := &Config{}
	if _, err := toml.DecodeFile(file, config); err != nil {
		log.Fatalln(err)
	}

	displays := config.Displays
	checkGetIders(displays, "显示屏(Displays)")

	pages := []*pb.Page{}
	for _, d := range displays {
		pages = append(pages, d.Pages...)
	}

	checkGetIders(pages, "页面(Pages)")

	blocks := []*pb.Block{}
	for _, p := range pages {
		blocks = append(blocks, p.Blocks...)
	}

	checkGetIders(blocks, "区块(Blocks)")

	images := []*pb.Images{}
	webs := []*pb.Web{}

	for _, i := range blocks {
		if i.Type == pb.Block_IMAGES {
			images = append(images, i.Images)
		}

		if i.Type == pb.Block_WEB {
			webs = append(webs, i.Web)
		}
	}

	checkGetIders(images, "图片(Images)")
	checkGetIders(webs, "网页(Web)")

	return &ConfigService{
		file:     file,
		config:   config,
		displays: displays,
		pages:    pages,
		blocks:   blocks,
		images:   images,
		Webs:     webs,
	}
}

// Save 保存.
func (s *ConfigService) Save() error {
	file, err := os.OpenFile(s.file, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0640)
	if err != nil {
		log.Fatalln(err)
	}
	defer file.Close()

	return toml.NewEncoder(file).
		Encode(s.config)
}

// GetDisplay 获取显示屏.
func (s *ConfigService) GetDisplay(id int32) (*pb.Display, error) {
	for _, c := range s.displays {
		if c.Id == id {
			return c, nil
		}
	}

	return nil, ErrorNotFound
}

// GetPage 获取页面.
func (s *ConfigService) GetPage(id int32) (*pb.Page, error) {
	for _, p := range s.pages {
		if p.Id == id {
			return p, nil
		}
	}

	return nil, ErrorNotFound
}

// GetBlock 获取块.
func (s *ConfigService) GetBlock(id int32) (*pb.Block, error) {
	for _, b := range s.blocks {
		if b.Id == id {
			return b, nil
		}
	}

	return nil, ErrorNotFound
}

// GetImages 获取图像.
func (s *ConfigService) GetImages(id int32) (*pb.Images, error) {
	for _, i := range s.images {
		if i.Id == id {
			return i, nil
		}
	}

	return nil, ErrorNotFound
}

// GetWeb 获取网页.
func (s *ConfigService) GetWeb(id int32) (*pb.Web, error) {
	for _, w := range s.Webs {
		if w.Id == id {
			return w, nil
		}
	}

	return nil, ErrorNotFound
}
